package com.antaohua.framework.web.interceptor;

import java.io.PrintWriter;
import java.lang.annotation.Annotation;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.antaohua.framework.web.utils.JsonResult;

public class ResultJsonErrorInterceptor extends HandlerInterceptorAdapter {

	private final static Log log = LogFactory.getLog(ResultJsonErrorInterceptor.class);
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {
		if(ex!=null){
			Boolean isResultJson = false;
			if("org.springframework.web.method.HandlerMethod".equals(handler.getClass().getName())){
				HandlerMethod  method = (HandlerMethod)handler;
				
				Annotation[]  annotations = method.getMethod().getAnnotations();
				for (Annotation annotation : annotations) {
					if(annotation.annotationType().isAssignableFrom(ResponseBody.class)){
						isResultJson = true;
						log.error("controller error",ex);
					}
				}
			}
			if(isResultJson){
				PrintWriter out = response.getWriter();
				JsonResult result = new JsonResult(JsonResult.STATUS_ERROR,ex.getMessage());
				out.println(JSON.toJSONString(result));
			}
		}
	}

}
